package com.ljh.androidTest;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class MainActivity extends Activity {
    String broker = "tcp://broker-cn.emqx.io:1883";
    String topic = "";//主题
    String clientid = "";//唯一ID
    int qos = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.ljh.androidTest.R.layout.activity_main);
        Button open = findViewById(com.ljh.androidTest.R.id.btn1);
        Button close = findViewById(com.ljh.androidTest.R.id.btn2);

        pushMessage("1");

        open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = "1";
                pushMessage(content);
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = "2";
                pushMessage(content);
            }
        });
    }

    private void pushMessage(String content) {
        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            // 连接
            client.connect(options);
            // 创建消息并设置 QoS
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            // 发布消息
            client.publish(topic, message);
            System.out.println("Message published");
            System.out.println("topic: " + topic);
            System.out.println("message content: " + content);
            // 关闭连接
            client.disconnect();
            // 关闭客户端
            client.close();
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    protected void onStop() {
        pushMessage("2");
        super.onStop();
    }
}